<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
/**
 * @var Mage_Page_Block_Html_Header $this
 */
?>
<header class="header-container">
	<section class="header">
		<article class="header-top">
			<?php echo $this->getChildHtml('topLinks') ?>
		</article>
		<article class="header-center">
			<section class="logo-home">
				<a href="<?php echo $this->getUrl('') ?>" title="<?php echo $this->getLogoAlt() ?>" class="logo"><img src="<?php echo $this->getLogoSrc() ?>" alt="<?php echo $this->getLogoAlt() ?>" /></a>
			</section>
			<!--end logo-->
			<?php if($this->helper('customer')->isLoggedIn() && $this->helper('gtgobbler/flashsales')->isActiveFlashsales()):?>
			<input type="hidden" value="1" id="activeSales"/>
			<section class="header-time" <?php if(!Mage::getStoreConfig('gobblersales/flashsales/showtimer')):?>style="display: none;"<?php endif?>>
				<p>
					sale ends:
				</p>
				<div id="saleEnds" class="countdown"></div>			
				<?php $timeDiff = Mage::getModel('gtgobbler/flash_sales')->getRemainTime();?>
				<script>
					jQuery(function(){						
						jQuery('#saleEnds').countdown({
							until: '<?php echo '+'.$timeDiff['second_diff']?>', 
							format: 'HMS',
							layout: '<ul class="countdown_row">'+
										'<li class="first">' +
											'<div class="time">' +
												'<span>{hnn}</span>' +
											'</div>' +
											'<h2>hour</h2>' +
											'<div class="line"></div>'+
										'</li>' +
										'<li>' +
											'<div class="time">' +
												'<span>{mnn}</span>' +
											'</div>' +
											'<h2>min</h2>' +	
											'<div class="line"></div>'+
										'</li>' +
										'<li class="last">' +
											'<div class="time">' +
												'<span>{snn}</span>' +
											'</div>' +
											'<h2>sec</h2>' +
											'<div class="line"></div>'+
										'</li>' +						
									'</ul>',
							onExpiry: function(){
								showSalesEndPopup();
							}
						}); 
						// jQuery('#saleEnds').countdown('pause');
					});
				</script>						
			</section>
			<?php endif?>
		</article>
		<article class="header-menu">
			<section class="header-menu-left">
				<h3>
					Shop by:
				</h3>
				
				<article class="menu-main">
					<?php if($this->helper('customer')->isLoggedIn() && $this->helper('gtgobbler/flashsales')->isActiveFlashsales()):?>
						<ul id="nav">
							<?php 
								$currentCategory = Mage::registry('current_category');								
								$isActive = false;								
								if(($currentCategory && $currentCategory->getId() != 11 && $currentCategory->getId() != 12)
									|| ($this->getRequest()->getParam('filter') == 'category'))
								{
									$isActive = true;
								}
							?>
							<li class="category <?php echo $isActive ? 'active' : ''?>">
								<?php 
									$mainCategory = Mage::getModel('catalog/category')
										->load(13);
										
									$categories = Mage::getResourceModel('catalog/category_collection')
										->addIsActiveFilter()
										->addAttributeToSelect('include_in_menu')
										->addAttributeToSelect('name')
										->addIdFilter($mainCategory->getChildren())
										->setOrder('position', Varien_Db_Select::SQL_ASC);
								?>
								<a href="<?php echo $this->getUrl('gtgobbler/shopby', array('_query' => array('filter' => 'category')))?>">category</a>
								<div class="menu-sub">
									<ul>
									<?php foreach($categories as $category):?>
										<li>
											<a href="<?php echo $category->getUrl()?>"><?php echo $category->getName()?></a>
										</li>
									<?php endforeach?>
									</ul>
								</div>								
							</li>
							<?php 
								$isActive = false;
								if($currentCategory && $currentCategory->getId() == 11){
									$isActive = true;
								}
							?>
							<li class="best-seller <?php echo $isActive ? 'active' : ''?>">
								<a href="<?php echo $this->getUrl('best-sellers')?>">best sellers</a>
							</li>
							<?php 
								$isActive = false;
								if($this->getRequest()->getParam('filter') == 'price'){
									$isActive = true;
								}
							?>
							<li class="nav-price <?php echo $isActive ? 'active' : ''?>">
								<a href="<?php echo $this->getUrl('gtgobbler/shopby', array('_query' => array('filter' => 'price', 'dir' => 'asc')))?>">price</a>
								<div class="menu-sub">
									<ul>
										<li class="asc">
											<a href="<?php echo $this->getUrl('gtgobbler/shopby', array('_query' => array('filter' => 'price', 'dir' => 'asc')))?>">Lowest to Highest</a>
										</li>
										<li class="desc">
											<a href="<?php echo $this->getUrl('gtgobbler/shopby', array('_query' => array('filter' => 'price', 'dir' => 'desc')))?>">Highest to Lowest</a>
										</li>
									</ul>
								</div>
							</li>
							<?php 
								$isActive = false;
								if($this->getRequest()->getParam('filter') == 'limitedstock'){
									$isActive = true;
								}
							?>
							<li class="limitstock <?php echo $isActive ? 'active' : ''?>">
								<a href="<?php echo $this->getUrl('gtgobbler/shopby', array('_query' => array('filter' => 'limitedstock')))?>">limited stock</a>
							</li>
							<li <?php if(Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier() == 'new-products') echo 'class="active"'?>>
								<a href="<?php echo $this->getUrl('new-products')?>">new</a>
							</li>
						</ul>
					<?php else:?>
						<ul id="nav" class="sales-end">							
							<li class="category">
								category
							</li>
							<li class="best-seller">
								best seller
							</li>
							<li class="nav-price">
								price
							</li>
							<li class="limitstock">
								limited stock
							</li>
							<li class="new-products">
								new
							</li>
						</ul>
					<?php endif?>					
				</article>
			</section>
			<!--end header menu lefet-->
			<section class="header-menu-right">
				<ul>					
					<li <?php if($this->getRequest()->getModuleName() == 'contacts') echo 'class="active"'?>>
						<a href="<?php echo $this->getUrl('contacts')?>">
						contact 
						</a>
					</li>
					<li <?php if(Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier() == 'about-us') echo 'class="active"'?>>
						<a href="<?php echo $this->getUrl('about-us')?>">
						about <span>|</span>
						</a>
					</li>
					<li <?php if(Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier() == 'home') echo 'class="active"'?>>
						<a href="<?php echo $this->getUrl('')?>">
						home <span>|</span>
						</a>
					</li>
					<?php if($this->helper('customer')->isLoggedIn()):?>
						<?php
							$isMyAccountActive = false;
							if($this->getRequest()->getModuleName() == "customer" || ($this->getRequest()->getModuleName() == 'gtgobbler' && $this->getRequest()->getControllerName() == 'customer_account')){
								$isMyAccountActive = true;
							}							
						?>
						<li <?php if($isMyAccountActive):?>class="active"<?php endif?>>							
							<a href="<?php echo $this->getUrl('customer/account')?>">
								my account <span>|</span>
							</a>
						</li>
					<?php endif?>
				</ul>				
			</section>
			<!--end header menu right-->
		</article>		
		<?php echo $this->getChildHtml('topContainer'); ?>
	</section>
	<section class="header-background"></section>
	<div class="no-display">
		<div id="loginPopup" class="lightbox">
			<input type="hidden" id="isLoggedIn" value="<?php if($this->helper('customer')->isLoggedIn()) echo '1'; else echo '0';?>"/>
			<header>
				<p>
					Start Shopping to
					<span>
						Save!
					</span>
				</p>
				<div></div>
			</header>
			
			<article class="popup-content">
				<div class="again"><span>Oops! You've been timed out. Please log in again.</span></div>
				<a href="#" class="modalClose">close x</a>
				<p>
					Log in
				</p>
				<form method="POST" id="loginForm">
					<ul class="form-list">
						<li>
							<div class="input-box email">
								<input type="text" name="login[username]" placeholder="email address" id="email" class="input-text validate-user-confirm required-entry validate-email" title="Email Address">
							</div>
						</li>
						<li>
							<div class="input-box pass">
								<input type="password" name="login[password]" autocomplete="off" class="input-text required-entry validate-user-confirm validate-password" placeholder="password" id="pass" title="Password">
							</div>
							<a target="_blank" href="<?php echo $this->getUrl('customer/account/forgotpassword')?>" class="forgot">Forgot Password?</a>
						</li>
					</ul>
					<div class="buttons-set">
						<button type="submit" class="button" title="Login" name="send" id="loginBtn" onClick="logInOkBaby()">
							<span>
								<span>
									login
								</span>
							</span>
						</button>
						<span class="please-wait" id="login-please-wait" style="display:none;">
							<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Please wait...') ?>" title="<?php echo $this->__('Please wait...') ?>" class="v-middle" /> <?php echo $this->__('') ?>
						</span>
						<p id="popupError"></p>
					</div>
					<a class="popup-register-link" target="_blank" href="<?php echo $this->getUrl('customer/account/create')?>">register</a>
				</form>
				<figure class="hugo">
					<img src="<?php echo $this->getSkinUrl('images/hugo.png')?>">
				</figure>
			</article>
		</div>
		<div id="salesEndPopup" class="lightbox">
			<p class="popup-header">We're Sorry, the sale is over!</p>
			<p class="popup-content">But don't worry, there'll be more to come! So keep your eyes peeled and stay tuned!</p>
			<img class="sales-end-monster" src="<?php echo $this->getSkinUrl('images/end-monster.png')?>"/>
			<button class="button" onclick="window.location = '<?php echo $this->getUrl('customer/account')?>'"><span><span>My Account</span></span></button>
		</div>
	</div>
	<input type="hidden" id="ajaxLoading" value="0"/>
	<script type="text/javascript">
		jQuery(function($) {
			$.extend($.modal.defaults, {
				'closeHTML': '',
				'opacity' : 60,
				'closeClass': "modalClose",
				'escClose': true,
				'overlayClose': true
			});
			
			jQuery('.products-grid li').each(function(){
				var myHeight = jQuery(this).outerHeight();
				var otherHeight = jQuery(this).parent().outerHeight();
				if(myHeight < otherHeight){
					var productNameBlock = jQuery(this).find('.product-name');
					productNameBlock.height(productNameBlock.height() + (otherHeight - myHeight));
				}
			});
			
			//change ajax flag to prevent duplice ajax request
			$('#ajaxLoading').ajaxStart(function(){
				$('#ajaxLoading').val(1);
			}).ajaxStop(function(){
				$('#ajaxLoading').val(0);
			});		
			
			<?php if($this->getRequest()->getParam('vcl')):?>
			jQuery('#loginPopup').modal();
			<?php endif?>			
			
			<?php 
				if(!Mage::helper('gtgobbler/flashsales')->isActiveFlashSales()){
					$module = $this->getRequest()->getModuleName();
					$controller = $this->getRequest()->getControllerName();
					$cmsIdentifier = Mage::getBlockSingleton('cms/page')->getPage()->getIdentifier();
					
					$allowModule = array('customer','sales','contacts','cms');
					$allowController = array('customer_account','address','sales_order');
					if((!in_array($module,$allowModule) && !in_array($controller,$allowController) || $cmsIdentifier == 'home') ){
						echo 'showSalesEndPopup();';
					}
				}			
			?>
			 
			initSharePopup();		

			jQuery.idleTimer(parseInt(<?php echo Mage::getStoreConfig('gobblergeneral/timeout/second')*1000?>));			
			jQuery(document).bind("idle.idleTimer", function(){
				if(!isLoggedIn())
					return;
				jQuery.ajax(correctProtocol('<?php echo $this->getUrl('customer/account/ajaxlogout')?>')).done(function(data){
					jQuery.modal.close();
					jQuery('#loginPopup').modal({
						containerId: 'timeout',
						close: false,
						onClose: function(){
							setTimeout(window.location.reload(),500);
						}
					});
					jQuery('#isLoggedIn').val(0);
				});
			});
			
			// jQuery('input[placeholder]').placeholder();			
		});
		
		jQuery(window).load(function(){
			initMoreChoice();
			jQuery('.sales-home-banner-container').css('overflow','visible');
		});
		
		jQuery(function(){
			//quickview tooltip
			jQuery('.quickview').each(function()
			{
				var self = this;
				var productId = this.id.replace('quickviewBtn-', '');
				jQuery(this).qtip(
				{					
					content: {						
						text: '<img class="throbber" src="<?php echo $this->getSkinUrl('images/opc-ajax-loader-black.gif') ?>" alt="Loading..." />'		
					},
					events: {						
						render: function(event, api){
							if(!isLoggedIn())
								return false;
							jQuery.ajax({
								url: correctProtocol('<?php echo $this->helper('gtgobbler/catalog ')->getQuickviewUrl()?>'),
								type: 'POST', 
								data: {id : productId},
								success: function(data, status) {									
									api.set('content.text', data);
									
									initSharePopup();
									
									initMoreChoice();
									
									if(jQuery('#tooltipMoreviewCount-' + productId).val() > 3){
										jQuery("#tooltipSlideContainer-" + productId).jCarouselLite({
											btnNext: "#scroll-right-" + productId,
											btnPrev: "#scroll-left-" + productId,
											visible: 3										
										});
									}else{
										decorateList('tooltipnoslide-' + productId);
									}
									
									
									jQuery('.chose_image_' + productId).click(function(e){
										e.preventDefault();

										var mainImage = jQuery('.main_image_' + productId);
										
										mainImage.data('position',jQuery(this).data('position'));
										
										var smallImageSrc = jQuery(this).attr('simg');
										var bigImageSrc = jQuery(this).attr('href');
										
										//add loading and change image
										var loading = jQuery('<div class="quickview-loading">Loading...</div>');
										if(mainImage.parent().find('.quickview-loading').length < 1){
											mainImage.find('img').attr('src', smallImageSrc);
											mainImage.find('img').load(function(){
												loading.remove();
											});
											mainImage.parent().append(loading);
										}										
									});
									
									jQuery('.main_image_' + productId).click(function(e){
										e.preventDefault();
										
										//hide quickview popup
										api.hide();
										
										var self = this;
										
										jQuery.fancybox.open(galleryUnique(jQuery('.chose_image_' + productId)),{
											helpers : {
												thumbs : {
													width  : 50,
													height : 50
												},
												title : {
													type: 'inside',
													position: 'top'
												}
											},
											loop: false,
											arrows: false,
											nextEffect: 'none',
											prevEffect: 'none',			
											index: typeof(jQuery(self).data('position')) == 'number' ? jQuery(self).data('position') : jQuery('#baseIndex_' + productId).val()
										});
									});
								}
							});
						},
						show: function(event, api) {
							//reposition if the quickview size overload window size
							var targetLeft = jQuery(api.elements.target).offset().left;
							var windowWidth = jQuery(window).width();
							if(targetLeft > (windowWidth/2)){								
								api.set('position.adjust.x', 50);
								api.set('style.tip.offset', 150);
							}
							
							jQuery(self).addClass('active');										
						},
						hide: function(event, api) {
							jQuery(self).removeClass('active');
						}
					},
					position: {
						at: 'top left', // Position the tooltip above the link
						my: 'bottom left',						
						effect: false, // Disable positioning animation
						adjust:{
							x: 49,
							y: 185
						},
						target: jQuery(self).parent()
					},
					show: {
						event: 'click',
						solo: true // Only show one tooltip at a time
						
					},
					hide: 'unfocus',
					style: {
						classes: 'ui-tooltip-quickview',
						tip: {
							corner: 'bottom left',
							mimic: 'center',
							width: 20,
							height: 10,
							offset: 15
						}
					}
				})
			})		 
			// Make sure it doesn't follow the link when we click it
			.click(function(event) { event.preventDefault(); });
		});		
		
		function correctProtocol(url){
			var currentProtocol = location.protocol;
			
			if(url.indexOf(currentProtocol) == -1){
				if(currentProtocol == 'http:'){
					return url.replace('https','http');
				}else{
					return url.replace('http','https');
				}
			}
			return url;
		}
		
		function galleryUnique(galleries) {
			var hash = {}, result = [];
			for ( var i = 0, l = galleries.length; i < l; ++i ) {
				if ( !hash.hasOwnProperty(galleries[i]) ) { //it works with objects! in FF, at least
					hash[ galleries[i] ] = true;
					result.push(galleries[i]);
				}
			}
			
			//sort the array based on data position
			result.sort(function(a,b){
				return jQuery(a).data('position') - jQuery(b).data('position');
			});
			
			return result;
		}
		
		function initMoreChoice(){			
			jQuery('.mcbutton').each(function(){
				var id = jQuery(this).attr('id');
				
				var productIdTmp = id.split('-');
				var productId = productIdTmp[productIdTmp.length - 1];
				
				var idPrefix = '';
				if(id.indexOf('popup') > 0){
					idPrefix = 'popup-';
				}else if(id.indexOf('banner') > 0){
					idPrefix = 'banner-';
				}
				
				var container = jQuery('#flavourc-' + idPrefix + productId);
				
				var buttonTimer = null;
				var containerTimer = null;
				
				// var parent = jQuery('#productContainer_' + productId);
				var parent = jQuery(this).parents('li');				
				
				jQuery(this).click(function(e){
					e.preventDefault();
					parent.addClass('on-top');					
					container.slideDown();
				}).mouseover(function(){
					if(buttonTimer !== null){						
						clearTimeout(buttonTimer);
						buttonTimer = null;
					}
					if(containerTimer !== null){
						clearTimeout(containerTimer);
						containerTimer = null;
					}		
				}).mouseout(function(){
					buttonTimer = setTimeout(function () {
						container.slideUp(function(){
							parent.removeClass('on-top');
						});						
					}, 500);
				});
				 
				container.hover(function(){
					if(buttonTimer !== null){						
						clearTimeout(buttonTimer);
						buttonTimer = null;
					}
					if(containerTimer !== null){
						clearTimeout(containerTimer);
						containerTimer = null;
					}					
				},function(){
					containerTimer = setTimeout(function () {
						container.slideUp(function(){
							parent.removeClass('on-top');
						});						
					}, 500);					
				}).click(function(){
					container.slideUp(function(){
						parent.removeClass('on-top');
					});	
				});
			});		
		}
		
		function initSharePopup(){			
			jQuery('.sharefriend-button').each(function()
			{				
				var self = this;				
				var tmpArray = self.id.split('-');
				var productId = tmpArray[tmpArray.length - 1];				
				jQuery(this).qtip(
				{
					content: {
						text: '<img class="throbber" src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="Loading..." />',
						title: {
							text: 'Tell A Friend!',
							button: true
						}
					},
					events: {
						render: function(event, api){
							jQuery.ajax({
								url: correctProtocol('<?php echo $this->helper('gtgobbler/catalog ')->getShareFriendUrl()?>'),
								type: 'POST', 
								data: {id : productId},
								success: function(data, status) {								
									api.set('content.text', data);									
									jQuery('#shareMessage_' + productId).autosize({append: "\n"});  
								}
							});
						},
						show: function(event, api) {
							if(!isLoggedIn()){
								alert('Please log in first.');
								event.preventDefault();
							}				
						}
					},
					position: {
						my: 'center', // ...at the center of the viewport
						at: 'center',
						target: jQuery(window)
					},
					show: {
						event: 'click', // Show it on click...
						solo: true, // ...and hide all other tooltips...
						modal: true // ...and make it modal
					},
					hide: false,
					style: 'ui-tooltip-share-popup'
				});
			});
		}
		
		function showLoginPopup() {
			if(isLoggedIn())
				return;
			jQuery.modal.close();
			jQuery('#loginPopup').modal();
		}
		
		function showSalesEndPopup(){
			jQuery('#salesEndPopup').modal({
				'escClose': false,
				'overlayClose': false
			});
		}

		function logInOkBaby() {
			jQuery('#loginForm').bind('submit', function(event) {
				event.preventDefault();
			});			
			jQuery('#popupError').fadeOut();
			var validator = new Validation('loginForm');
			if (validator.validate()) {
				jQuery('#loginForm .buttons-set').addClass('disabled');
				jQuery('#login-please-wait').show();
				jQuery.ajax({
					type : 'POST',
					url: correctProtocol('<?php echo $this->helper('gtgobbler/customer ')->getAjaxLogInUrl()?>'),
					data: jQuery('#loginForm').serialize(),
					dataType : 'JSON',
					success: function(data){
						jQuery('#login-please-wait').hide();
						jQuery('#loginForm .buttons-set').removeClass('disabled');						
						if(data.error == true){
							jQuery('#popupError').html(data.msg).fadeIn();							
							return;
						}else{							
							jQuery.modal.close();
							// jQuery('#isLoggedIn').val(1);
							// var html = jQuery(data.html);
							// var topLinks = jQuery('.header-top');
							// var cartSidebar = jQuery('.block-cart');
							// topLinks.html(html.find('#ajax-top-links').html());
							// cartSidebar.html(html.find('#ajax-cart-sidebar .block-cart').html());
							if(data.redirect)
							window.location = data.redirect;
						}
					}
				});
			}
		}
		
		function isLoggedIn(){
			return jQuery('#isLoggedIn').val() == 1;
		}
		
		function isThereAjaxRequest(){
			return jQuery('#ajaxLoading').val() == 1;
		}
		
		function increaseQty(isList, isPopup, isBanner, productId, maxQty){			
			var idPrefix = '';
			if(isList)
				idPrefix = 'qty-list-';
			else if(isPopup == true){
				idPrefix = 'qty-popup-';
			}else if(isBanner == true){
				idPrefix = 'qty-banner-';
			}else{
				idPrefix = 'qty-';
			}
			var currentValue = parseInt($(idPrefix + productId).value);
			if(maxQty > 0){
				if(currentValue < maxQty){
					currentValue += 1;
				}else{
					var messageTemplate = "<?php echo Mage::helper('cataloginventory')->__("The maximum quantity allowed for purchase is %s.")?>";
					
					if(idPrefix == 'qty-popup-')
					{
						messageTemplate = 'Sorry, but everyone\'s entitled to %s each!';
					}
					
					addNotify(productId,idPrefix, messageTemplate.replace('%s', maxQty));
					return;
				}
			}else{
				currentValue += 1;
			}				
			$(idPrefix + productId).value = currentValue;			
		}
		
		function decreaseQty(isList, isPopup, isBanner, productId){			
			var idPrefix = '';
			if(isList)
				idPrefix = 'qty-list-';
			else if(isPopup == true){
				idPrefix = 'qty-popup-';
			}else if(isBanner == true){
				idPrefix = 'qty-banner-';
			}else{
				idPrefix = 'qty-';
			}
			var currentValue = parseInt($(idPrefix + productId).value);
			if(currentValue > 1)
				currentValue -= 1;
			$(idPrefix + productId).value = currentValue;			
		}
		
		//add to cart, default is list mode
		var allowAddCart = 1;
		function addToCartAjax(productId, isList, isPopup, isBanner, superAttributeId, superAttributeValue){
			if(isLoggedIn()){
				if(allowAddCart == 0){
					// alert('Please wait other request done.');
					return;
				}
				allowAddCart = 0;				
				
				var idPrefix = '';
				if(isList)
					idPrefix = 'qty-list-';
				else if(isPopup)
					idPrefix = 'qty-popup-';
				else if(isBanner)
					idPrefix = 'qty-banner-';
				else
					idPrefix = 'qty-';
				jQuery('#sidebarLoadingFlag').show();
				var productData = {'product' : productId, 'qty' : $(idPrefix + productId).value};
				if(typeof(superAttributeId) != 'undefined'){
					var postString = "{'super_attribute[" + superAttributeId + "]' : '" + superAttributeValue + "'}";
					var configurableData = eval('(' + postString + ')');
					jQuery.extend(productData, configurableData);
				}
				jQuery.ajax({
					type : 'POST',
					url: correctProtocol('<?php echo $this->helper('gtgobbler/checkout ')->getAddToCartUrl()?>'),
					data: productData,
					dataType : 'JSON',
					success: function(data){
						try{
							jQuery('#sidebarLoadingFlag').hide();
							
							//update cart sidebar															
							var cartSidebarContent = jQuery('.block-cart .block-content');							
							cartSidebarContent.html(jQuery(data.html).html());
							
							if(data.error == true){
								if(data.redirect){
									window.location.href = data.redirect;
								}
								if(idPrefix == 'qty-popup-')
								{
									var longMsg = data.msg.match(/Wow, you must really like this, but everyone's entitled to \d+ each./);										
									
									if(longMsg){
										var maxQty = longMsg[0].match(/\d+/g);
										data.msg = data.msg.replace(/Wow, you must really like this, but everyone's entitled to \d+ each./g, "Sorry, but everyone's entitled to " + maxQty + " each!");
									}
								}
								
								addNotify(productId,idPrefix,data.msg.replace(/\\n/g, '\n'));														
							}else{
								var sidebarNotify = '<div class="added-item">'	+							
														'<h3> item added </h3>' +
														'<span> &gt; </span>' +
													'</div>';
								
								sidebarNotify = jQuery(sidebarNotify).insertBefore('.block-cart .actions');
								
								setTimeout(function(){
									sidebarNotify
										.fadeOut(function(){
											jQuery(this).remove()
										});				
								}, 10000);
								
								addNotify(productId,idPrefix,data.msg);
							}
							
							allowAddCart = 1;							
						}catch(e){
							alert(e);
							allowAddCart = 1;
						}	
					},
					error: function(){
						jQuery('#sidebarLoadingFlag').hide();
						alert('There is an error in your request.');
						allowAddCart = 1;
					}
				});							
			}else{
				alert('You must log in to add cart.');
			}
		}
		
		function addNotify(pid, idPrefix, msg){
			var selector = '';
			if(idPrefix == 'qty-list-'){
				selector = '#an-';
			} else if(idPrefix == 'qty-banner-'){
				selector = '#an-banner';
			}else if(idPrefix == 'qty-popup-'){
				selector = '#an-popup-';
			}else{
				showAlert('error', msg);
				return;
			}
			
			var messages = msg.split('\n');
			
			var msgContainer = jQuery(selector + (idPrefix == 'qty-banner-' ? '' : pid));				
			
			notifyQueue(msgContainer, messages, 0);	
		}
		
		//show error messages item by item
		function notifyQueue(container, messages, interval){
			interval = parseInt(interval);
			
			if(interval == messages.length)
				return;
				
			container.html(messages[interval]).fadeIn();
			
			setTimeout(function(){
				container.fadeOut(function(){
					interval += 1;
					notifyQueue(container, messages, interval);
				});				
			}, 10000);	
		}
		
		function showAlert(type, message){
			var messages = message.split('\n');
			
			var i = 0;
			var messagesHtml = '';
			for(i;i<messages.length;i++){
				messagesHtml += '<li>' +
									'<span>' + messages[i] + '</span>' +
								'</li>';
			}
			
			var messageHtml = '<ul class="messages">' +
								'<li class="' + type + '-msg">' +
									'<ul>' +
										messagesHtml
									'</ul>' +
								'</li>' +
							'</ul>';
			
			if(jQuery('.messages').length == 1){
				jQuery('.messages').remove();
			}
			
			jQuery(messageHtml).insertAfter('.breadcrumbs');
			
			setTimeout(function(){
				jQuery('.messages').fadeOut();
			}, 10000);
		}
		
		var lastValidMessage = '';
		var storeLimit = <?php echo Mage::getStoreConfig('gobblersales/sharefriend/limit_characters')?>;
		function processMessage(productId)
		{
			var message = jQuery('#shareMessage_' + productId);
			var maxLength = storeLimit;
			var remaining = maxLength - message.val().length;
			if (remaining < 0) {
				message.val(lastValidMessage);
				remaining = maxLength-message.val().length;
			} else {
				lastValidMessage = message.val();
			}
			jQuery('#limitCount_' + productId).html(remaining);			
		} 
		
		function shareFriendNow(productId){
			jQuery('#shareFriendForm_' + productId).bind('submit', function(event) {
				event.preventDefault();
			});
			var validator = new Validation('shareFriendForm_'+productId);
			if (validator.validate()) {
				jQuery('#shareFriendForm_' + productId + ' .actions button').hide();
				jQuery('#sf-please-wait-' + productId).show();
				jQuery.ajax({
					url: correctProtocol('<?php echo $this->helper('gtgobbler/catalog ')->getShareFriendPostUrl()?>'),
					type: 'POST',
					dataType: 'JSON', 
					data: jQuery('#shareFriendForm_' + productId).serialize(),
					success:function(data){						
						jQuery('#shareFriendForm_' + productId + ' .actions button').show();
						jQuery('#sf-please-wait-' + productId).hide();
						
						alert('Email has been sent!');
						
						jQuery('#share-button-'+productId).qtip('api').hide();
					},
					error: function(){
						jQuery('#shareFriendForm_' + productId + ' .actions button').show();
						jQuery('#sf-please-wait-' + productId).hide();
						
						alert('An error occur!');
					}
				});
			}
			
		}

		Validation.add('validate-phone-number', 'Please enter valid Singapore phone number.', function(v){
			return Validation.get('IsEmpty').test(v) || /^[6|8|9]\d{7}$/.test(v);
		});		
	</script>
</header>